package com.beagle.njddapp.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.beagle.njddapp.BuildConfig;
import com.beagle.njddapp.R;
import com.beagle.njddapp.base.ApiService;
import com.beagle.njddapp.base.BaseApplication;
import com.beagle.njddapp.base.RetrofitHttp;
import com.beagle.njddapp.bean.UserInfoBean;
import com.beagle.njddapp.bean.VersionBean;
import com.beagle.njddapp.core.UserService;
import com.beagle.njddapp.net.BaseHttpResponse;
import com.beagle.njddapp.net.HttpResponseObserver;
import com.beagle.njddapp.net.RxSchedulers;
import com.beagle.njddapp.ui.activity.owner.MessageActivity;
import com.beagle.njddapp.utils.PrefsManager;
import com.beagle.njddapp.weight.dialog.UpgradeDialog;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.beagle.njddapp.core.UserService.ROLE;
import static com.beagle.njddapp.core.UserService.ROLE_DIRVER;
import static com.beagle.njddapp.core.UserService.ROLE_OIL;

/**
 * @author hxx
 * @date 2021-03-05 20:07
 * 启动页
 */
public class SplanshActivity extends AppCompatActivity implements UpgradeDialog.UpgradeDialogHandleCallback {

    private UpgradeDialog upgradeDialog;
    private VersionBean versionBean;
    private Handler handler;
    private boolean isToMain;
    private boolean isPermission;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splansh);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission_group.STORAGE) !=
                PackageManager.PERMISSION_GRANTED) {
            //向用户请求权限，指定请求码
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.ACCESS_COARSE_LOCATION
                    ,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_BACKGROUND_LOCATION,Manifest.permission.CAMERA}, 1);
        } else {
            toMian();
        }
        handler=new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isToMain&&isPermission){
                    isToMain=true;
                    realToMain();
                }
            }
        },5000);
    }
    private void toMian() {
        isPermission=true;
        ApiService apiService = RetrofitHttp.provideRetrofit().create(ApiService.class);
        apiService.version().compose(RxSchedulers.compose()).safeSubscribe(new HttpResponseObserver<BaseHttpResponse<VersionBean>>() {
            @Override
            public void success(BaseHttpResponse<VersionBean> versionBeanBaseHttpResponse) {
                if (versionBeanBaseHttpResponse!=null&&versionBeanBaseHttpResponse.data!=null){
                    versionBean=versionBeanBaseHttpResponse.data;
                    PackageManager pm = getApplicationContext().getPackageManager();//context为当前Activity上下文
                    PackageInfo pi = null;
                    try {
                        int code ;
                        pi = pm.getPackageInfo(getApplicationContext().getPackageName(), 0);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                            code = (int) pi.getLongVersionCode();
                        } else {
                            code = pi.versionCode;
                        }
                        if (Integer.parseInt(versionBean.getVersionCode())>code){
                            showUpgrade();
                        }else {
                            realToMain();
                        }

                    } catch (Exception e) {
                        realToMain();
                    }
                }else {
                    realToMain();
                }
            }

            @Override
            public void error(int code, String message) {
                realToMain();
            }
        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                //请求成功
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                   toMian();
                } else {
                    Toast.makeText(this, "请开启相关权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void showUpgrade() {
        isToMain=true;
        handler.removeCallbacksAndMessages(null);
        if (upgradeDialog==null){
            upgradeDialog=new UpgradeDialog(this);
        }
        upgradeDialog.setUpgradeDialogHandleCallback(this);
        upgradeDialog.show();
    }




    @Override
    public void upgrade() {
        ApiService apiService = RetrofitHttp.provideRetrofit().create(ApiService.class);
        apiService.downloadAPk(versionBean.getAppAddress()).compose(RxSchedulers.compose()).safeSubscribe(new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {

            }
            @Override
            public void onNext(ResponseBody responseBody) {
                File file=writeResponseBodyToDisk(responseBody);
                if ( file!=null){
                    installApk(getApplicationContext(),file);
                }else {
                    realToMain();
                }
            }
            @Override
            public void onError(Throwable e) {
                realToMain();
            }

            @Override
            public void onComplete() {

            }
        });
    }
    private void realToMain() {
        String token = PrefsManager.getInstance(BaseApplication.getInstance()).getString(UserService.TOKEN);
        LogUtils.d(token);
        if (TextUtils.isEmpty(token)) {
            isToMain=true;
            handler.removeCallbacksAndMessages(null);
            startActivity(new Intent(this,LoginActivity.class));
            finish();
        } else {
            UserService.getInstance().setToken(token);
            UserService.getInstance().setRole(PrefsManager.getInstance(BaseApplication.getInstance()).getInt(ROLE, 1));
            getUserInfo();
        }
    }



    private void getUserInfo() {
        ApiService apiService = RetrofitHttp.provideRetrofit().create(ApiService.class);
        apiService.getUserInfo().compose(RxSchedulers.compose()).safeSubscribe(new HttpResponseObserver<BaseHttpResponse<UserInfoBean>>() {
            @Override
            public void success(BaseHttpResponse<UserInfoBean> userInfoBeanBaseHttpResponse) {
                if (userInfoBeanBaseHttpResponse != null && userInfoBeanBaseHttpResponse.data != null) {
                    isToMain=true;
                    handler.removeCallbacksAndMessages(null);
                    UserInfoBean infoBean = userInfoBeanBaseHttpResponse.data;
                    UserService.getInstance().setUserInfoBean(userInfoBeanBaseHttpResponse.data);
                    if (TextUtils.isEmpty(infoBean.getUserName())) {
                        isToMain=true;
                        startActivity(new Intent(SplanshActivity.this, BasicUserInfoActivity.class));
                        finish();
                    }else  if (0 == infoBean.getUserRole()) {
                        isToMain=true;
                        startActivity(new Intent(SplanshActivity.this, ChooseRoleActivity.class));
                        finish();
                    } else{
                        isToMain=true;
                        startActivity(new Intent(SplanshActivity.this,MainActivity.class));
                        finish();
                    }

                } else {
                    isToMain=true;
                    handler.removeCallbacksAndMessages(null);
                    UserService.getInstance().setUserInfoBean(userInfoBeanBaseHttpResponse.data);
                    startActivity(new Intent(SplanshActivity.this,MainActivity.class));
                    finish();
                }
            }

            @Override
            public void error(int code, String message) {
                isToMain=true;
                handler.removeCallbacksAndMessages(null);
                UserService.getInstance().clear();
                startActivity(new Intent(SplanshActivity.this,MainActivity.class));
                finish();

            }
        });
    }


    public  void installApk(Context context,File apkFile) {
        if (upgradeDialog!=null){
            upgradeDialog.dismiss();
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//需要开新的任务栈，不然安装完成无法弹出“完成”、“打开”页面
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本
            Uri apkUri = FileProvider.getUriForFile(context, "com.beagle.njddapp", apkFile);  //包名.fileprovider
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }
    private File writeResponseBodyToDisk(ResponseBody body) {
        try {
            File futureStudioIconFile = new File(getExternalFilesDir(null) + File.separator + "njdd.apk");

            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                byte[] fileReader = new byte[4096];

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(futureStudioIconFile);

                while (true) {
                    int read = inputStream.read(fileReader);

                    if (read == -1) {
                        break;
                    }

                    outputStream.write(fileReader, 0, read);

                    fileSizeDownloaded += read;

                }

                outputStream.flush();

                return futureStudioIconFile;
            } catch (IOException e) {
                return null;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isToMain=true;
        handler.removeCallbacksAndMessages(null);
    }


    @Override
    public void cancle() {
        realToMain();
    }
}
